package io.github.iogogogo.web.handler;

import io.github.iogogogo.commons.support.wrapper.BaseResult;
import io.github.iogogogo.commons.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.resource.NoResourceFoundException;

/**
 * Created by tao.zeng on 2024/11/17.
 */
@Slf4j
@ResponseBody
@ControllerAdvice
public class GlobalExceptionHandler implements BaseResult {

    @ExceptionHandler(value = Exception.class)
    public Object exceptionHandler(Exception exception) throws Exception {
        if (exception instanceof BizException e)
            return result(e.getCode(), e.getMessage());

        if (exception instanceof NoResourceFoundException e)
            return result(e.getStatusCode().value(), e.getMessage());

        log.error("【异常】", exception);
        return result(HttpStatus.INTERNAL_SERVER_ERROR.value(), null, exception.getMessage());
    }
}
